<?php

namespace App\Model;
use App\User;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;

/**
 * App\Model\WeChat
 *
 * @mixin \Eloquent
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\WeChat newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\WeChat newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\WeChat query()
 */
class WeChat extends Model
{
    /**
     * 获取微信公众号配置
     * @return \EasyWeChat\OfficialAccount\Application
     */
    public static function getWeChatOfficialAccount()
    {
        $options = \Config::get('wechat');
        return Factory::officialAccount($options['official_account']['default']);
    }

    /**
     * 获取公众号用户列表
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function getWeChatUserListAll()
    {
        $app =  self::getWeChatOfficialAccount();
        return $app->user->list();
    }

    /**
     * 获取用户信息
     * @param $open_id
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function getWeChatUser($open_id)
    {
        $app =  self::getWeChatOfficialAccount();

        return $app->user->get($open_id);

    }

    public static function getWeChatPayment()
    {
        $options = \Config::get('wechat');
        return Factory::payment($options['payment']['default']);
    }

    public static function getWeChatPaymentWord()
    {
        $options = \Config::get('wechat');
         return Factory::work($options);
    }

    /**
     * @param $open_id
     * @param $url
     * @param $template
     * @param $data
     * @return mixed
     * @throws InvalidArgumentException
     */
    public static function sendWeChatMsg($open_id, $template, $url, $data)
    {
        $app = self::getWeChatOfficialAccount();

        return $app->template_message->send([
            'touser' => $open_id,
            'url' => $url,
            'template_id' => $template,//env('WECHAT_OFFICIAL_TEMPLATE_ID'),
            'data' => $data,
        ]);

    }

    // 生成图片上传素材

    public function buildImage($type = 0, $open_id)
    {
        $user_detail =  UserDetail::where('open_id', $open_id)->first();
        if ($type == 1){
            $img = \Image::make(public_path('images/'.env('BOY')));
        }else{
            $img = \Image::make(public_path('images/'.env('GIRL')));
        }

        $name = $user_detail->wechat_name;
        if (mb_strlen($name) >4){
            $name =  mb_substr($name,0,4,"UTF8")."...";
        }

        // 姓名
        $img->text($name, 550, 170, function ($font){
            $font->file(public_path('size/msyhbd.ttc'));
            $font->size(36);
            $font->color('#1A1A1A');
            $font->align('left');
            $font->valign('top');
        });

        // 成绩
        $num = [99, 98, 97, 96, 95, 94 , 93];

        $img->text($num[array_rand($num)],550, 230, function ($font){
            $font->file(public_path('size/SEGOESC.TTF'));
            $font->size(40);
            $font->color('#FF3030');
            $font->align('left');
            $font->valign('top');
        });

        // 外表
        $img->text($this->surface($type),55, 410,function ($font){
            $font->file(public_path('size/msyhbd.ttc'));
            $font->size(24);
            $font->color('#c1bdb6');
            $font->align('left');
            $font->valign('top');
        });

        // 智商
        $img->text($this->iq($type),410, 410,function ($font){
            $font->file(public_path('size/msyhbd.ttc'));
            $font->size(24);
            $font->color('#c1bdb6');
            $font->align('left');
            $font->valign('top');
        });

        // 个性

        $img->text($this->individuality($type),55, 550,function ($font){
        $font->file(public_path('size/msyhbd.ttc'));
        $font->size(24);
        $font->color('#c1bdb6');
        $font->align('left');
        $font->valign('top');
    });

        // 恋爱
        $img->text($this->love($type),410, 550,function ($font){
            $font->file(public_path('size/msyhbd.ttc'));
            $font->size(24);
            $font->color('#c1bdb6');
            $font->align('left');
            $font->valign('top');
        });

        // 评论

        $img->text($this->comment($type),50, 720,function ($font){
            $font->file(public_path('size/msyhbd.ttc'));
            $font->size(32);
            $font->color('#c1bdb6');
            $font->align('left');
            $font->valign('top');
        });

        $path = sprintf("/data/upload/%s/%s/%s", date('Y', time()), date('m', time()),
            date('d', time()));
        $filePath = public_path($path);

        if(!is_dir($filePath))
        {
            mkdir($filePath,0700, true);
        }
        $fileName = time()."{$user_detail->id}".'.'.'jpg';

        $filePath = $filePath.'/'.$fileName;

        $img->save($filePath);

        // 上传微信素材
       $media_id =   $this->uploadWeChatImg($filePath);

       $user_detail->media_id = $media_id;
       $user_detail->media_path = env('apiUrl') .'/' . $path .'/'. $fileName;
       $user_detail->save();
        $user = User::where('id', $user_detail->user_id)->first();
        if ($user->phone){
            return  $user_detail->media_path;
        }
       return '';
    }
    public function uploadWeChatImg($path)
    {
        $app = WeChat::getWeChatOfficialAccount();
        try {
            $res = $app->material->uploadImage( $path );
        } catch (InvalidArgumentException $e){
            Log::error ($e);
        }
        return $res['media_id'];
    }


    //微信答题随机匹配数据
    // 外表
    public function surface($type = 0)
    {
        $boyArr = [
            '体表堂堂，清秀俊逸',
            '帅到人神共愤',
        ];

        $girlArr = [
            '回眸一笑百媚生',
            '高冷御姐范',
            '巧笑倩兮 美目盼兮',

        ];
        // 男生
        if ($type == 1){
            return  $boyArr[array_rand($boyArr)];
        }
        return $girlArr[array_rand($girlArr)];
    }

    //智商
    public function iq($type = 0)
    {
        $boyArr = [
            '天生太清醒，努力活糊涂',
            '智商很高，但没有绝顶'
        ];
        $girlArr = [
            '聪明过人',
            '大智若愚',
            '大事不糊涂，小事不计较',

        ];

        // 男生
        if ($type == 1){
            return  $boyArr[array_rand($boyArr)];
        }
        return $girlArr[array_rand($girlArr)];
    }
    //个性
    public function individuality($type = 0)
    {
        $boyArr = [
            '有斗志，不服输',
            '心软，但吃软不吃硬'
        ];

        $girlArr = [
            '有一颗少女心',
            '不爱计较，
更不爱记仇',
            '偶尔也想嘤嘤嘤',
        ];

        // 男生
        if ($type == 1){
            return  $boyArr[array_rand($boyArr)];
        }
        return $girlArr[array_rand($girlArr)];
    }

    // 恋爱
    public function love($type = 0)
    {
        $boyArr = [
            '在一起越久，越懂得珍惜' ,
            '情调满满，浪漫十足',
        ];
        $girlArr = [
            '爱起来飞蛾扑火，毫不掩饰。',
            '在一起越久，越懂得珍惜。',
            '爱时全身心投入，抱着天长地久
的状态相处。'
        ];

        // 男生
        if ($type == 1){
            return  $boyArr[array_rand($boyArr)];
        }
        return $girlArr[array_rand($girlArr)];
    }

    // 评语

    public function comment($type = 0)
    {
        $boyArr = [
                '外表看着是一个铁血真汉子，但是内心非常柔软。
是一个正能量满满，偶尔会口是心非的傲娇星人。
做事总是希望尽善尽美，有计划地规划。',
                '你是一个聪明且自信的人，很善于学习，再加上
会说话，对人热情，也很自然的博得了大家的喜
爱。'
        ];
        $girlArr = [
            '你是一个有些敏感和不安的人，会因为很小
的事情丧失安全感。 你念旧，同时又对未来
感到不安，每当失败的时候就深深的沮丧和懊
悔。对于你来 说，安全感是很重要的东西。
很重视爱情 和友情，希望身边的朋友都能够
很好地相处，很喜欢和朋友们一起 玩。',
            '你表面看起来很强悍，但内心还有温柔细腻的
一面，你属于擅长规 划自己的优秀人物。看着
高龄之花，其实有个热心肠，就是不善言表。
品味很高，对于自己是严格要求的。',
            '你热情，温柔，但是心情不好的时候会对人非
常冷漠，不希望别人 给你太多约束。奉行唯有美
食与睡眠不可辜负，同时也是一个拖延症晚期患
者。'
        ];

        // 男生
        if ($type == 1){
            return  $boyArr[array_rand($boyArr)];
        }
        return $girlArr[array_rand($girlArr)];
    }

    public  function getUserCode($open_id)
    {
        $user_detail  = UserDetail::where('open_id', $open_id)->first();
        $user = User::where('id',$user_detail->user_id)->first();
        $user_activity = UserActivity::where('user_id', $user->id)->first();

        if (isset($user_activity->media_id)){
             return $user_activity->media_id;
        }else{
            $path = $this->saveHeadPortrait($user_detail, $user_detail->head_portrait, 90);
           return  $this->ActivityMediaBuildImage($user_detail , $path);
        }
    }

    //生成活动图片
    public function ActivityMediaBuildImage(UserDetail $userDetail ,$path)
    {
        $img = \Image::make(public_path('images/activity.jpg'));
        // 插入二维码
        $img->insert($path, 'bottom-left',68,35);
        // 插入头像
        $img->insert(public_path($userDetail->local_head_portrait), '');

        $path = sprintf("/data/upload/%s/%s/%s", date('Y', time()), date('m', time()),
            date('d', time()));
        $filePath = base_path('public' . $path);
        if (!is_dir($filePath)) {
            mkdir($filePath, 0700, true);
        }
        $imgName = \Illuminate\Support\Str::random(16) . time() . '.jpg';
        $imgPath = $filePath.'/'.$imgName;
        $img->save($imgPath);
        // 上传微信素材
        $media_id =   $this->uploadWeChatImg($imgPath);
        $user_activity = new UserActivity();
        $user_activity->create([
            'user_id' => $userDetail->user_id,
            'type' => 1,
            'keyword' => '海报',
            'media_id' => $media_id,
            'media_path' => $imgPath
        ]);

        return $user_activity->media_id;
    }


    public function saveUserHeadPortrait(User $user, $path, $size)
    {
        $user_detail = UserDetail::where('user_id', $user->id)->first();
        $url =  $this->saveHeadPortrait($user_detail, $path, $size);
        $user->qr_code = $url;
        $user->save();
        return $user->qr_code;
    }

    public function saveHeadPortrait(UserDetail $user_detail, $path, $size)
    {
        $img = Common::curl_file_get_contents($path);

        $imgName = \Illuminate\Support\Str::random(16) . time() . $user_detail->user_id . '.jpg';
        $imgPath = base_path('public') . '/' . $imgName;
        file_put_contents($imgPath, $img);

        $url = 'http://' . $_SERVER['HTTP_HOST'] . '/front/oauth?user_id=' . $user_detail->user_id."&poster=1";
        $qrcode = new  BaconQrCodeGenerator();
        $path = sprintf("/data/upload/%s/%s/%s", date('Y', time()), date('m', time()),
            date('d', time()));
        $filePath = base_path('public' . $path);
        if (!is_dir($filePath)) {
            mkdir($filePath, 0700, true);
        }
        $fileName = \Illuminate\Support\Str::random(16) . time()  . '.jpg';
        $filePath = $filePath . '/' . $fileName;
        $qrcode->format('png')->size($size)->merge('/public/' . $imgName, .15)->margin(0)->generate($url, $filePath);
        unlink(public_path($imgName));
        $user_detail->local_head_portrait = $path . '/' . $fileName;
        $user_detail->save();
        return  env('apiUrl') . $path . '/' . $fileName;
    }



}
